package com.example.j202411.repository;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;


import com.example.j202411.Model.BusResponse;
import com.example.j202411.Model.BusResponse.BusInfo;
import com.example.j202411.service.BusService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class BusRepository {
    private static final String BASE_URL = "https://api.lolimi.cn/";
    private BusService busService;

    public BusRepository() {
        Gson gson = new GsonBuilder()
                .setLenient() // 启用宽容模式
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
        busService = retrofit.create(BusService.class);
    }

    public LiveData<List<BusInfo>> getBusInfo(String city, String line, String direction) {
        MutableLiveData<List<BusInfo>> data = new MutableLiveData<>();
        busService.getBusInfo("json", city, line, direction).enqueue(new Callback<BusResponse>() {
            @Override
            public void onResponse(@NonNull Call<BusResponse> call, @NonNull Response<BusResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    data.setValue(response.body().getData());
                } else {
                    Log.e("BusRepository", "Error getting data from API: " + response.code() + " " + response.message());
                    try {
                        Log.d("BusRepository", "Response body: " + response.errorBody().string());
                    } catch (Exception e) {
                        Log.e("BusRepository", "Error reading response body: " + e.getMessage());
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<BusResponse> call, @NonNull Throwable t) {
                Log.e("BusRepository", "Error fetching data from API", t);
            }
        });

        return data;
    }
}
